package com.xs.shop.orders.service.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xs.shop.common.exceptions.BusinessException;
import com.xs.shop.common.exceptions.enums.Resp;
import com.xs.shop.goods.feign.api.GoodsClient;
import com.xs.shop.orders.model.entity.Cart;
import com.xs.shop.orders.model.entity.Order;
import com.xs.shop.orders.service.handlers.BaseContextHandler;
import com.xs.shop.orders.service.mapper.OrderMapper;
import com.xs.shop.orders.service.service.CartService;
import com.xs.shop.orders.service.service.OrderItemService;
import com.xs.shop.orders.service.service.OrderService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  订单服务实现类
 * </p>
 *
 * @author xs,zyx
 * @since 2025-07-16
 */
@Slf4j
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Resource
    private CartService cartService;

    @Resource
    private OrderItemService orderItemService;

    @Resource
    private GoodsClient goodsClient;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addOrder() {
        // 从购物车里获取商品信息
        List<Cart> cartItems = cartService.getCart();
        log.info("购物车商品：{}", cartItems);

        // 但在这里我们用购物车里第一个条目的id作为订单id
        BigDecimal amount = this.orderItemService.addOrderItem(cartItems);

        // 创建订单
        Order order = new Order();
        order.setMemberId(BaseContextHandler.get());
        order.setId(cartItems.get(0).getId());
        order.setTotalAmount(amount);
        String orderNo = generateOrderNo();  // 生成唯一订单编号
        order.setOrderNo(orderNo);
        this.save(order);
        // 创建订单后就要把结算掉的商品从购物车里删掉
        this.cartService.deleteCart();
    }
    // 订单编号生成
    private String generateOrderNo() {
        String timestamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        int random = (int) (Math.random() * 9000) + 1000;
        return timestamp + random;
    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean deleteOrder(Long id) {
        if (id == null) {
            throw new BusinessException(Resp.INVALID_PARAM);
        }
        return this.removeById(id);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Order updateOrder(Order order) {
        if (order == null || order.getId() == null) {
            throw new BusinessException(Resp.INVALID_PARAM);
        }
        order.setUpdatedAt(new Date());
        this.updateById(order);
        return order;
    }

    @Override
    public Order getOrderById(Long id) {
        if (id == null) {
            throw new BusinessException(Resp.INVALID_PARAM);
        }
        return this.getById(id);
    }


    @Override
    public List<Order> getOrdersByLoginId() {
        Long memberId = BaseContextHandler.get();
        if (memberId == null) {
            throw new BusinessException(Resp.INVALID_PARAM);
        }
        // 使用pageOrder方法并传入memberId参数
        Page<Order> orderPage = this.pageOrder(1, Integer.MAX_VALUE, null, null, memberId, null);
        // 返回订单列表
        return orderPage.getRecords();
    }
    @Transactional(rollbackFor = Exception.class)
    public boolean clearOrder() {
        Long memberId = BaseContextHandler.get();
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Order::getMemberId, memberId);
        // 删除购物车项
        return this.remove(wrapper);
    }

    @Override
    public Page<Order> pageOrder(Integer current, Integer pageSize, Long orderId, String orderNo, Long memberId, Integer status) {
        LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();
        // 按订单ID查询
        if (orderId != null) {
            queryWrapper.eq(Order::getId, orderId);
        }
        // 按订单号模糊查询
        if (StringUtils.hasText(orderNo)) {
            queryWrapper.like(Order::getOrderNo, orderNo);
        }
        // 按会员ID查询
        if (memberId != null) {
            queryWrapper.eq(Order::getMemberId, memberId);
        }
        // 按订单状态查询
        if (status != null) {
            queryWrapper.eq(Order::getStatus, status);
        }
        // 按创建时间倒序
        queryWrapper.orderByDesc(Order::getCreatedAt);
        return this.page(new Page<>(current, pageSize), queryWrapper);
    }
}
